# -*-coding:utf-8 -*-
#
# Created on 2019/5/13, by felix
#

from base.views import BaseViewSet

from .models import CommandInfo, TemplateInfo
from .serializers import TemplateInfoSerializer


# 200 外键+choice
class TemplateInfoViewSet(BaseViewSet):
    """template-bak-test info"""
    queryset = TemplateInfo.objects.filter(is_deleted=False).order_by('-id')
    serializer_class = TemplateInfoSerializer
    http_method_names = ['get', 'post', 'put', 'delete']

    # 210 反序列化
    def create(self, request, *args, **kwargs):
        # 序列化验证，必须要验证的字段 require=True, null=True, blank=True
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        command_id = request.data.get('command_id')
        template_type = request.data.get('template_type')
        price = request.data.get('price')

        if not command_id:
            return self.render_to_json_response(status=1, msg="请输入command_id")
        if not template_type:
            return self.render_to_json_response(status=1, msg="请输入template_type")

        # 外键关联，需要取实例对象
        queryset_command = CommandInfo.objects.filter(id=command_id).first()
        if not queryset_command:
            return self.render_to_json_response(status=1, msg="没有找到该command")

        data = {
            'template_type': template_type,
            'command': queryset_command,
            'price': price
        }
        queryset = self.get_queryset().create(**data)

        # 序列化返回
        serializer = self.get_serializer(queryset)
        return self.render_to_json_response(data=serializer.data)

    # 220 反序列化 更新
    def update(self, request, *args, **kwargs):
        # 序列化验证，必须要验证的字段 require=True, null=True, blank=True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        pk = kwargs.get('pk')
        try:
            # 方式1：固定的字段, 更改
            # self.get_queryset().filter(pk=pk).update(
            #     template_type=request.data.get('template_type'),
            #     command_id=request.data.get('command_id'),
            #     price=request.data.get('price')
            # )

            # 方式2：不固定的字段
            self.get_queryset().filter(id=pk).update(**request.data)
        except Exception as e:
            return self.render_to_json_response(status=1, msg="update失败:%s" % str(e))

        # 序列化返回
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return self.render_to_json_response(data=serializer.data)

    # 230 外键字段，过滤
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        # 字段过滤
        template_type = request.query_params.get('template_type')
        command_name = request.query_params.get('command_name')
        if template_type:
            queryset = queryset.filter(template_type=template_type)

        # 跨表查询，模糊查找
        if command_name:
            queryset = queryset.filter(command__name__icontains=command_name)

        # 存在分页，?page=2&page_size=1  序列化分页的数据 page
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        # 否则，序列化全部数据 queryset
        serializer = self.get_serializer(queryset, many=True)
        return self.get_paginated_response(data=serializer.data)
